<template>
  <div id="GovernmentService">
    <img src="https://nfzjszlb.jst.zj.gov.cn/serverfile/zheliban/icon/ZLJ/PC/top.png" />
    <img src="https://nfzjszlb.jst.zj.gov.cn/serverfile/zheliban/icon/ZLJ/PC/banner.png" />
    <div v-if="show" style="width: 1550px;margin: 0 auto">
      <p style="height: 106px;line-height: 106px;font-size: 32px;font-family: Songti SC;font-weight: 900;">
        请选择业务办理类型
      </p>
      <div style="width: 1550px;height: 570px;background: #FFFFFF;box-shadow: 0px 6px 10px 0px rgba(0, 0, 0, 0.14);padding: 20px;">
        <p style="font-size: 24px;font-family: Songti SC;font-weight: 900;margin-bottom: 20px;">
          请选择业务类型（单选）
        </p>
        <el-radio-group v-model="radio">
          <div style="width: 472px;height: 51px;border: 1px solid #B0B0B0;border-radius: 4px;float: left;margin-bottom: 20px;margin-right: 20px;line-height: 58px;padding-left: 20px;" v-for="(item,index) in radioArr" :key="index">
            <el-radio :label="item">{{item}}</el-radio>
          </div>
        </el-radio-group>
        <div style="margin-top:22vh;width: 100%; text-align: center;">
          <el-button @click="show = false" style="width: 100px;" type="primary" round>确定</el-button>
        </div>
      </div>
    </div>
    <div v-else style="width: 1550px;margin: 0 auto">
      <div style="padding: 20px 0;text-align: center;">
        <img src="https://nfzjszlb.jst.zj.gov.cn/serverfile/zheliban/icon/ZLJ/PC/1.png" />
        <ul style="width: 1021px;margin: 0 auto">
          <li v-for="(item,index) in technologicalData" :key="index" style="width: 255px;float: left;text-align: center;">
            {{item}}
          </li>
        </ul>
      </div>
      <div style="width: 1550px;height: 570px;background: #FFFFFF;box-shadow: 0px 6px 10px 0px rgba(0, 0, 0, 0.14);padding: 20px;">
        <p style="font-size: 24px;font-family: Songti SC;font-weight: 900;margin-bottom: 20px;">
          人员基本信息
        </p>
        <div style="width: 100%;padding: 0 10%;overflow:auto;height:40vh;">
          <el-form :rules="rules" :inline="true" :model="formInline" class="demo-form-inline" label-width="120px">
            <el-form-item label="户主姓名" prop="houseapplicant">
              <el-input style="width:23vw;" v-model="formInline.houseapplicant" placeholder="户主姓名"></el-input>
            </el-form-item>
            <el-form-item label="身份证号码" prop="certificatecode">
              <el-input style="width:23vw;" v-model="formInline.certificatecode" placeholder="身份证号码" @change="handleGetCityData"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="applyphone">
              <el-input style="width:23vw;" v-model="formInline.applyphone" placeholder="手机号"></el-input>
            </el-form-item>
            <el-form-item label="所属市" prop="S">
              <el-select style="width:23vw;" v-model="formInline.S" placeholder="请选择所属市" @change="changeCity">
                <el-option v-for="item in CityColumns" :key="item.CITYCODE" :label="item.CITYNAME" :value="item.CITYCODE">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属县(区)" prop="X">
              <el-select style="width:23vw;" v-model="formInline.X" placeholder="请选择" @change="changeXian">
                <el-option v-for="item in XianColumns" :key="item.CITYCODE" :label="item.CITYNAME" :value="item.CITYCODE">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属镇" prop="town">
              <el-select style="width:23vw;" v-model="formInline.town" placeholder="请选择" @change="changeTown">
                <el-option v-for="item in TownColumns" :key="item.CITYCODE" :label="item.CITYNAME" :value="item.CITYCODE">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属村" prop="CUN">
              <el-select style="width:23vw;" v-model="formInline.CUN" placeholder="请选择">
                <el-option v-for="item in CunColumns" :key="item.CITYCODE" :label="item.CITYNAME" :value="item.CITYCODE">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="建房类型" prop="buildtype">
              <el-select style="width:23vw;" v-model="formInline.buildtype" placeholder="请选择" @change="onConfirmBUILDTYPE">
                <el-option v-for="item in BUILDTYPEcolumns" :key="item.DICID" :label="item.DICNAME" :value="item.DICID">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="建房理由" prop="buildreason">
              <!-- <el-input  style="width:23vw;" v-model="formInline.buildreason" placeholder="建房理由"></el-input> -->
              <el-select style="width:23vw;" v-model="formInline.buildreason" placeholder="请选择">
                <el-option v-for="item in JFLYcolumns" :key="item" :label="item" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否联建" prop="If_ljf">
              <el-select style="width:23vw;" v-model="formInline.If_ljf" placeholder="请选择" @change="onConfirm">
                <el-option v-for="item in columns1" :key="item.DICID" :label="item.DICNAME" :value="item.DICID">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div v-if="IsLG==1">
            <div style="margin-bottom: 15px">
              <el-button type="primary" size="small" @click="freeAdd">新增</el-button>
              <el-button type="primary" size="small" @click="haddleEdit">修改</el-button>
              <el-button type="primary" size="small" @click="handleDelete">删除</el-button>
            </div>
            <div>
              <el-table :data="tableData" border size="mini" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="45">
                </el-table-column>
                <el-table-column type='index' label="序号" align="center" width="45">
                </el-table-column>
                <el-table-column prop="XM" align="center" label="姓名">
                </el-table-column>
                <el-table-column prop="SFZH" align="center" label="身份证号">
                </el-table-column>
                <el-table-column prop="phone" align="center" label="联系电话">
                </el-table-column>
                <!-- <el-table-column prop="sexx" align="center" label="性别"> -->
                <!-- </el-table-column> -->
                <!-- <el-table-column prop="JTZZ" align="center" label="家庭住址"> -->
                <!-- </el-table-column> -->
              </el-table>
            </div>
          </div>
        </div>
        <div style="margin-top:2vh;width: 100%; text-align: center;">
          <el-button @click="show = true" style="width: 100px;" round>上一步</el-button>
          <el-button style="width: 100px;" type="primary" round @click="BtnSaveFormData"> 下一步</el-button>
        </div>
      </div>
    </div>
    <el-dialog :title="dialogTitle" :visible.sync="showDialog" width='36%' center>
      <el-form :inline="true" :model="tableFrom" class="demo-form-inline" label-width="120px">
        <el-form-item label="姓名" prop="XM">
          <el-input style="width:23vw;" v-model="tableFrom.XM" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="SFZH">
          <el-input style="width:23vw;" v-model="tableFrom.SFZH" placeholder="身份证号"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input style="width:23vw;" v-model="tableFrom.phone" placeholder="联系电话"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveBtn">确 定</el-button>
        <el-button @click="cancelBtn">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  dataServerOpenDataView,
  InsertDataView,
  PrepareCreateProcess,
  FileServerProxy,
  CreateProcess,
  PlatSendTask,
  FileServerUpload
} from '@/utils/api'
import { v4 as uuidv4 } from 'uuid';
export default {
  data () {
    //验证电话号码
    var checkTel = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'));
      } else {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error('请输入正确的电话号码！'));
        }
      }
    };
    //身份证号验证
    var peopleID = (rule, code, callback) => {
      var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "惠州", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 " };
      var tip = ""
      var pass = true
      if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
        tip = "身份证号格式错误"
        pass = false;
      } else if (!city[code.substr(0, 2)]) {
        // tip = "地址编码错误"
        tip = "身份证输入错误"
        pass = false
      } else {
        // 18位身份证需要验证最后一位校验位
        if (code.length === 18) {
          code = code.split('')
          // ∑(ai×Wi)(mod 11)
          // 加权因子
          var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
          // 校验位
          var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]
          var sum = 0
          var ai = 0
          var wi = 0
          for (var i = 0; i < 17; i++) {
            ai = code[i]
            wi = factor[i]
            sum += ai * wi
          }
          var last = parity[sum % 11];
          if (parity[sum % 11] != code[17]) {
            // tip = "校验位错误"
            tip = "身份证输入错误!"
            pass = false
          }
        }
      }
      if (!pass) {
        callback(new Error(tip))
      } else {
        callback()
      }
    };
    return {
      tableFrom: {
        XM: '',
        SFZH: '',
        sexx: '',
        phone: '',
        JTZZ: '',
        To_row_guid: '',
      },
      dialogTitle: '',
      showDialog: false,
      formInline: {
        houseapplicant: '',
        certificatecode: '',
        applyphone: '',
        S: '',
        X: '',
        town: '',
        CUN: '',
        buildtype: '',
        buildreason: '',
        If_ljf: ''
      },
      tableData: [],
      technologicalData: ["申请", "选图选工匠", "签订合同", "竣工验收"],
      show: true,
      radio: '',
      radioArr: [
        "农房新建",
        "农房改扩建",
        "危房改造",
        "经营流转",
        "经营流转",
        "地名牌办理"
      ],
      rules: {
        houseapplicant: [{ required: true, message: '请输入户主姓名', trigger: 'blur' }],
        // certificatecode: [{required: true, message: '请输入身份证号码', trigger: 'blur'}],
        certificatecode: [{ required: true, validator: peopleID, trigger: 'blur' }],
        applyphone: [{ required: true, validator: checkTel, trigger: 'blur' }],
        // applyphone: [{required: true, message: '请输入手机号', trigger: 'blur'}],
        S: [{ required: true, message: '请输入所属市', trigger: 'blur' }],
        X: [{ required: true, message: '请输入所属县(区)', trigger: 'blur' }],
        town: [{ required: true, message: '请输入所属镇', trigger: 'blur' }],
        // CUN:[{required: true, message: '请输入所属村', trigger: 'blur'}],
        buildtype: [{ required: true, message: '请输入建房类型', trigger: 'blur' }],
        buildreason: [{ required: true, message: '请输入建房理由', trigger: 'blur' }],
        If_ljf: [{ required: true, message: '请输入是否联建', trigger: 'blur' }],
      },
      CityColumns: [],
      XianColumns: [],
      TownColumns: [],
      CunColumns: [],
      BUILDTYPEcolumns: [],
      columns1: [],
      IsLG: 0,
      multipleSelection: [],
      JFLYcolumns: ['分户新建/无房新建', '危房翻建', '按照规划迁址新建住房']
    }
  },
  watch: {
    certificatecode: {
      handler (curVal, oldVal) {
        // 实现input连续输入，只发一次请求
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          if (this.formInline.certificatecode != '') {
            this.handleGetCityData(curVal)
          }
        }, 500)
      },
      deep: true,
      immediate: true
    }
  },
  mounted () {
    this.getCityOpenDataView()
    this.getBUILDTYPEcolumns()
    this.getcolumns1()
  },
  methods: {
    //根据身份证信息获取是哪个地市
    handleGetCityData: async function (data) {
      let params = {
        "accessCode": "4f54f932615d11ec87416805cab640a0",
        "cityCode": "",
        "appKey": "6738b790-69e8-11ec-a673-6805cab640a0",
        "params": { "czrkgmsfhm": this.formInline.certificatecode }
      }
      const res = await FileServerProxy(params);
      // res.data.datas[0].DATA
      this.formDataTR.S = res.data.data.datas[0].ELC_LICENCE_STRUCT.DATA.CZRKCSDSSX
      this.formDataTR.X = res.data.data.datas[0].ELC_LICENCE_STRUCT.DATA.CZRKJGSSX
      this.formDataTR.town = res.data.data.datas[0].ELC_LICENCE_STRUCT.DATA.XZJD
      this.formDataTR.CUN = res.data.data.datas[0].ELC_LICENCE_STRUCT.DATA.CJWH
    },
    handle1: async function (data) {
      let parms = {
        wfGuid: '{9FF1C524-B55F-4A45-83B3-6EA46CF32092}',
        entityRowGuid: data,
        token: window.localStorage.getItem('token')
      }
      const res = await PrepareCreateProcess(parms);
      //   this.sendData.push()
      //   let obj = {}
      //   res.data.SendData.forEach(item => {
      //     if (item.PTNID != -1&&item.) {
      //       obj = item
      //     }
      //   })
      //打开用户选择界面
      setTimeout(() => {
        this.$router.push({
          path: "/qianming",
          query: {
            data2: res.data.SendData,
            data1: data
          }
        });
      }, 1000)
      //   this.handle2(data, res.data.SendData[1])
    },
    BtnSaveFormData: async function () {
      if (this.formInline.houseapplicant == '' || this.formInline.houseapplicant == 'null' ||
        this.formInline.certificatecode == '' || this.formInline.certificatecode == 'null' ||
        this.formInline.applyphone == '' || this.formInline.applyphone == 'null' ||
        this.formInline.S == '' || this.formInline.S == 'null' ||
        this.formInline.X == '' || this.formInline.X == 'null' ||
        this.formInline.town == '' || this.formInline.town == 'null' ||
        // this.formInline.CUN==''||this.formInline.CUN=='null' ||
        this.formInline.buildtype == '' || this.formInline.buildtype == 'null' ||
        this.formInline.buildreason == '' || this.formInline.buildreason == 'null' ||
        this.formInline.If_ljf == '' || this.formInline.If_ljf == 'null'
      ) {
        this.$message({
          type: "error",
          message: "请输入必选项！",
        });
      } else {
        // let formData = {}
        let aaa = 0
        // if (this.nowIndex == 0) {
        //   formData = this.formData
        aaa = 35
        // } else {
        //   formData = this.formDataTR
        //   aaa = 36
        // }
        let uuid1 = uuidv4()
        this.formInline.row_guid = uuid1
        let params = {

          dataGuid: '01103ebf-a884-4282-b996-78dd64196946',
          // strParams: JSON.stringify([this.formData]),
          // entityRowGuid: uuid1,window.localStorage.getItem('userId')
          strParams: JSON.stringify([this.formInline]),
          'house_apply.SQFS': aaa,
          NHID: window.localStorage.getItem('userId'),
          token: window.localStorage.getItem('token')
        }
        const res = await InsertDataView(params)
        if (res.data.Success == true) {
          this.getTableData()
          this.clearData()
          this.$message({
            type: "success",
            message: "保存成功!",
          })
          // this.handle1(uuid1)
          // setTimeout(() => {
          //   this.$router.push({
          //     path: "/ChooseCraftsman",
          //   });
          // }, 2000)
          // setTimeout(() => {
          //   this.$router.push({
          //     path: "/qianming",
          //   });
          // }, 2000)
        }
      }
    },
    clearData () {
      this.formInline = {
        houseapplicant: '',
        certificatecode: '',
        applyphone: '',
        S: '',
        X: '',
        town: '',
        CUN: '',
        buildtype: '',
        buildreason: '',
        If_ljf: ''
      }
    },
    // 保存表格数据
    getTableData: async function () {
      let params = {
        dataGuid: 'a9125fd3-4d34-4732-b722-76dc06e6b38c',
        strParams: JSON.stringify(this.tableData),
        token: window.localStorage.getItem('token')
      }
      const res = await InsertDataView(params)
    },
    //删除
    handleDelete: function () {
      if (this.multipleSelection.length < 1) {
        this.$message({
          type: "error",
          message: "请选择一行数据",
        });
      } else {
        this.$confirm("此操作将永久删除该信息, 是否继续?", "提示", {
          cancelButtonClass: "btn-custom-cancel",
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
          .then(() => {
            this.multipleSelection.forEach((item) => {
              let ids = this.tableData.forEach((ele, index) => {
                if (ele.name == item.name) {
                  return true
                }
              })
              this.tableData.splice(ids, 1)
            });
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          })
          .catch(() => {
            this.$message({
              type: "error",
              message: res.data.msg,
            });
          });
      }
    },
    saveBtn () {
      this.tableData.push(this.tableFrom)
      this.tableData = Array.from(new Set(this.tableData))
      this.cancelBtn()
    },
    cancelBtn () {
      this.tableFrom = {
        name: '',
        sfzh: '',
        iphone: '',
        jtdz: '',
      }
      this.showDialog = false
    },
    haddleEdit () {
      if (this.multipleSelection.length != 1) {
        this.$message({ type: 'error', message: '请选择一条数据进行修改!' });
      } else {
        // this.tableFrom = JSON.parse(JSON.stringify(this.multipleSelection[0])) 
        this.tableFrom = this.multipleSelection[0]
        this.showDialog = true;
        this.dialogTitle = '修改';
      }
    },
    freeAdd () {
      this.showDialog = true;
      this.dialogTitle = '新增';
    },
    handleSelectionChange (val) {
      this.multipleSelection = val;
    },
    onConfirm (item) {
      if (item == 5) {
        this.IsLG = 1
      } else {
        this.IsLG = 0
      }
    },
    getcolumns1: async function () {
      this.columns1 = []
      let dataGuid = '86d6eb80-8bcb-49f6-b5c3-462ac1ae585d'
      let searchObject = []
      let token = window.localStorage.getItem('token')
      const res = await dataServerOpenDataView(dataGuid, searchObject, token)
      this.columns1 = res.data.Data
    },
    getBUILDTYPEcolumns: async function () {
      this.BUILDTYPEcolumns = []
      let dataGuid = 'db35edee-88e0-4fae-b14a-868ed4beb1d9'
      let searchObject = []
      let token = window.localStorage.getItem('token')
      const res = await dataServerOpenDataView(dataGuid, searchObject, token)
      this.BUILDTYPEcolumns = res.data.Data
    },
    getCityOpenDataView: async function () {
      this.CityColumns = []
      let dataGuid = 'e9c98787-4966-4365-80b0-c1cc678c6f85'
      let searchObject = []
      let token = window.localStorage.getItem('token')
      const res = await dataServerOpenDataView(dataGuid, searchObject, token)
      this.CityColumns = res.data.Data
    },
    changeCity (item) {
      this.getXianOpenDataView(item)
    },
    getXianOpenDataView: async function (data) {
      this.XianColumns = []
      let dataGuid = '77fdf2b0-0eb5-4243-a0a4-6185299ccd34'
      let searchObject = encodeURIComponent(JSON.stringify([{ "field": "pid", "value": data, "operator": "=" }]))
      let token = window.localStorage.getItem('token')
      const res = await dataServerOpenDataView(dataGuid, searchObject, token)
      this.XianColumns = res.data.Data
    },
    changeXian (item) {
      this.getTownOpenDataView(item)
    },
    getTownOpenDataView: async function (data) {
      this.TownColumns = []
      let dataGuid = '24d07248-ba49-4b82-9029-b5eccaff179d'
      let searchObject = encodeURIComponent(JSON.stringify([{ "field": "pid", "value": data, "operator": "=" }]))
      let token = window.localStorage.getItem('token')
      const res = await dataServerOpenDataView(dataGuid, searchObject, token)
      this.TownColumns = res.data.Data
    },
    changeTown (item) {
      this.getCunOpenDataView(item)
    },
    getCunOpenDataView: async function (data) {
      this.CunColumns = []
      let dataGuid = 'd3aaed7c-84ee-4de3-b70e-07fe188cdc8e'
      let searchObject = encodeURIComponent(JSON.stringify([{ "field": "pid", "value": data, "operator": "=" }]))
      let token = window.localStorage.getItem('token')
      const res = await dataServerOpenDataView(dataGuid, searchObject, token)
      this.CunColumns = res.data.Data
    },
    onConfirmBUILDTYPE (value) {
      if (value == 12) {
        this.JFLYcolumns = ['危房翻建']
      } else if (value == 14) {
        this.JFLYcolumns = ['分户新建/无房新建', '危房翻建', '按照规划迁址新建住房']
      }
    },
  }
}
</script>
<style lang="scss">
#GovernmentService {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}
</style>
